//
//  PoiSearchViewController.m
//  FootPrint
//
//  Created by 秦 东方 on 4/10/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "PoiSearchViewController.h"
#import "NVPopoverView.h"
#import "FilterCell.h"
#import "MerchantCell.h"
#import "PIODetailViewController.h"

@interface PoiSearchViewController ()

@end

@implementation PoiSearchViewController

@synthesize filterController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _parser = [[SearchMerchantParser alloc]init];
        [_parser setDelegate:self];
        
        _parser2 = [[SearchMerchantParser2 alloc]init];
        [_parser2 setDelegate:self];

        
        _favParser = [[FavMerchantParser alloc]init];
        _favParser.delegate = self;
    }
    return self;
}



- (void)setMode:(PoiOpenMode)openMode{
    _mode = openMode;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _arrMer = [[NSMutableArray alloc]init];
    
    filterController.delegate = self;
    filterController.filterStyle = NVFilterOnOffSwitchStyle;
    filterController.filter2NeedsDarkTabImage = YES;
    
    filterController.filterText1 = @"选择城市";
    filterController.filterText2 = @"选择区县";
    filterController.filterText3 = @"选择商圈";
    
//    [filterController setEnable:NO buttonIndex:1];
//    [filterController setEnable:NO buttonIndex:2];
//    [filterController setEnable:NO buttonIndex:3];
   
    [_tableViewMerchant setDataSource:self];
    [_tableViewMerchant setDelegate:self];
    
    //_textFieldFilter.delegate = self;
    [_textFieldFilter addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _filterType = 1;
    _isEnd = false;
    _nextCur = 0;
    [_parser requestFilter:[GConfig getUserId] cityName:nil subCity:nil busiCircle:nil type:nil];

    
}

#pragma mark Server Receive
- (void)didFinishReqFilter:(MerchantPropertyResponseMessage*)respFilter{
    
    if(nil == respFilter || [respFilter resultCode] != 0){
        [[[iToast makeText:@"服务器出错，未能取得分类信息"] setDuration:2000] show];
        return;
    }
    
    if(_filterType == 1){
        self.cityMsg = respFilter;
        self.districtMsg = nil;
        self.circleMsg = nil;
    }
    
    if(_filterType == 2){
        self.districtMsg = respFilter;
        self.circleMsg = nil;
    
    }
    
    if(_filterType == 3){
        self.circleMsg = respFilter;
    }
    
}
- (void)failReqFilter{
    [[[iToast makeText:@"服务器出错，未能取得过滤信息"] setDuration:2000] show];
}


- (void)didfinishReqMer:(MerchantQueryResponseMessage*)respMerchant{
    if(nil == respMerchant || [respMerchant resultCode] != 0){
        [[[iToast makeText:@"服务器出错，未能取得商户信息"] setDuration:2000] show];
        return;
    }
    _isEnd = [respMerchant isEnd];
    int count = [[respMerchant merchant] count];
    _nextCur += count;
    for(int i=0; i<count; i++){
        [_arrMer addObject:[respMerchant merchantAtIndex:i]];
    }
    [_tableViewMerchant reloadData];
}

- (void)failReqMer{
    //[[[iToast makeText:@"服务器出错，未能取得商户信息"] setDuration:2000] show];
    [_tableViewMerchant reloadData];
}


- (void)didfinishReqMer2:(MerchantQueryResponseMessage*)respMerchant{

    if(nil == respMerchant || [respMerchant resultCode] != 0){
        [[[iToast makeText:@"服务器出错，未能取得商户信息"] setDuration:2000] show];
        return;
    }
    _isEnd = [respMerchant isEnd];
    int count = [[respMerchant merchant] count];
    _nextCur += count;
    for(int i=0; i<count; i++){
        [_arrMer addObject:[respMerchant merchantAtIndex:i]];
    }
    [_tableViewMerchant reloadData];
}

- (void)failReqMer2{
 [_tableViewMerchant reloadData];
}

//- (BOOL)textField:(UITextField *)aTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//	NSString *newString = nil;
//	if (range.length == 0) {
//		newString = [aTextField.text stringByAppendingString:string];
//	} else {
//		NSString *headPart = [aTextField.text substringToIndex:range.location];
//		NSString *tailPart = [aTextField.text substringFromIndex:range.location+range.length];
//		newString = [NSString stringWithFormat:@"%@%@",headPart,tailPart];
//	}
//    
//    NSLog(@"%d = %d", range.location, range.length);
//    NSLog(@"%@ = %@", string, newString);
//    
//    return YES;
//}


- (void)textFieldDidChange:(UITextField*) textField
{
    if (textField.text.length > 0 && textField.markedTextRange == nil) {
        self.filterStr = [textField text];
        _nextCur = 0;
        _isEnd = NO;
        [_arrMer removeAllObjects];
        [_tableViewMerchant reloadData];
        
        //NSLog(@"%@", textField.text);
        [_parser2 requestMerchant:[GConfig getUserId] cityName:_curCity districtName:_curDistrict busiCircle:_curCircle type:nil subType:nil startIndex:_nextCur filter:_filterStr];
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    _selDelegate = nil;
    [filterController release];
    [_tableViewMerchant release];
    [_tableViewFilter release];
    [_textFieldFilter release];
    [super dealloc];
}

- (void)filterController:(NVFilterController *)controller touchedFilter:(FilterType)filterType{
    [_textFieldFilter resignFirstResponder];
    if(filterType == FilterType1 && controller.filter1NeedsOn){
        
        if(nil == _cityMsg || _cityMsg.city.count < 1){
            _showingIndex = 0;
            [self.filterController resetFilterBtnsStates];
            return;
        }
        
        _filterArray = _cityMsg.city;
       // [_tableViewFilter reloadData];
        _tableView = [[UITableView alloc]init];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];

        NVPopoverView *popoverView = [self setUpPopoverViewAppearanceForComponenetsView:_tableView];
        
        [popoverView showPopoverViewInView:filterController.filterViewSection3
                                  position:NVPopoverPositionBelow
                                  animated:NO];
        _showingIndex = 1;


    } else if(filterType == FilterType2 && controller.filter2NeedsOn){
        if(nil == _districtMsg || [[_districtMsg district] count] < 1){
            [self.filterController resetFilterBtnsStates];
            return;
        }
        _filterArray = _districtMsg.district;
        _tableView = [[UITableView alloc]init];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        
        NVPopoverView *popoverView = [self setUpPopoverViewAppearanceForComponenetsView:_tableView];
        
        [popoverView showPopoverViewInView:filterController.filterViewSection3
                                  position:NVPopoverPositionBelow
                                  animated:NO];
        _showingIndex = 2;

    } else if(filterType == FilterType3 && controller.filter3NeedsOn){
        if(nil == _circleMsg || _circleMsg.businessCircle.count < 1){
            [self.filterController resetFilterBtnsStates];
            return;
        }
        _filterArray = _circleMsg.businessCircle;
        _tableView = [[UITableView alloc]init];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        
        NVPopoverView *popoverView = [self setUpPopoverViewAppearanceForComponenetsView:_tableView];
        
        [popoverView showPopoverViewInView:filterController.filterViewSection3
                                  position:NVPopoverPositionBelow
                                  animated:NO];
        _showingIndex = 3;
    }
}

- (NVPopoverView *)setUpPopoverViewAppearanceForComponenetsView:(UIView *)componentsView
{
    NVPopoverView *retPopoverView = [NVPopoverView sharedPopoverView];
    retPopoverView.delegate=self;
    retPopoverView.componentsView = componentsView;
    return retPopoverView;
}


- (void)popoverViewDidAppear:(NVPopoverView *)popOverView
{
}

- (void)popoverViewDidDismiss:(NVPopoverView *)popOverView
{
    [self.filterController resetFilterBtnsStates];
    _showingIndex = 0;
}

#pragma mark datasouce and delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if(tableView == _tableViewMerchant){
        if(_isEnd){
            return [_arrMer count];
        } else {
            return [_arrMer count] + 1;
        }
    }
    
    return _filterArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(tableView == _tableViewMerchant){
    
        if(indexPath.row == [_arrMer count]){
            
            [_parser requestMerchant:[GConfig getUserId] cityName:_curCity districtName:_curDistrict busiCircle:_curCircle type:nil subType:nil startIndex:_nextCur filter:_filterStr];
            
            NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"LoadingCell" owner:self options:nil];
            UITableViewCell* cell = (UITableViewCell*)[arr objectAtIndex:0];
            UIActivityIndicatorView *ai = (UIActivityIndicatorView *)[cell viewWithTag:1];
            [ai startAnimating];
            return cell;
        }
        
        static NSString *identify = @"merchantCell";
        
        MerchantCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
        if(nil == cell){
            cell = [[[MerchantCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify] autorelease];
        }
       
        MerchantMessage* mer = [_arrMer objectAtIndex:indexPath.row];
        [cell updateCell:mer];
        return cell;
    }
    
    static NSString *identify = @"filterCell";
    FilterCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if(nil == cell){
        cell = [[[FilterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify] autorelease];
    }
    NSInteger index = indexPath.row ;
    NSString* title = [_filterArray objectAtIndex:index];
    [cell setTextStr:title];
    
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _tableViewMerchant){
        return 65;
    }
    return 55;
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_textFieldFilter resignFirstResponder];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [_textFieldFilter resignFirstResponder];
    
    if(indexPath.row == [_arrMer count]){
        return;
    }
    
    if(tableView == _tableViewMerchant){
        
        [self.tableViewMerchant deselectRowAtIndexPath: indexPath animated:YES];
        
       // int index = indexPath.row;
        _curIndex = indexPath.row;
        
        if(_mode == ModeChoose){
            
            PIODetailViewController * poiVC = [[[PIODetailViewController alloc] initWithNibName:@"PIODetailViewController" bundle:nil] autorelease];
            [poiVC setSelDelegate:_selDelegate];
            
            UINavigationController * navVc = ((UIViewController*)self.selDelegate).navigationController;
            [navVc pushViewController:poiVC animated:YES];
            
            MerchantMessage* mer = [_arrMer objectAtIndex:_curIndex];
            [poiVC updatePOIInfo:mer];
            poiVC.btnChoose1.hidden = YES;
            return;
        } else {
            
            UIActionSheet* sheet = [[[UIActionSheet alloc] initWithTitle:nil
                                                                delegate:self
                                                       cancelButtonTitle:nil
                                                  destructiveButtonTitle:nil
                                                       otherButtonTitles:nil] autorelease];
            [sheet addButtonWithTitle:@"查看"];
            [sheet addButtonWithTitle:@"添加到收藏"];
            [sheet addButtonWithTitle:@"取消"];
            sheet.cancelButtonIndex = [sheet numberOfButtons] - 1;
            [sheet showInView:self.view];
        }
        
        
        
//        MerchantMessage* mer = [_arrMer objectAtIndex:indexPath.row];
//        [_selDelegate didSelPOI:mer];
        
    } else {
    
        int index = indexPath.row;
        NSString* title = [_filterArray objectAtIndex:index];
        if(_showingIndex == 1){
            
            [NVPopoverView slideOutPopoverView];
            [self.filterController resetFilterBtnsStates];
            if([[self.filterController filterText1] compare:title] == NSOrderedSame ){
                return;
            }
            [self.filterController setFilterText1:title];
            _curCity = title;
            _curDistrict = nil;
            _curCircle = nil;
            
            _filterType = 2;
            _circleMsg = nil;
            _districtMsg = nil;
            [_parser requestFilter:[GConfig getUserId] cityName:title subCity:nil busiCircle:nil type:nil];

            
            [self.filterController setFilterText2:@"选择区县"];
            [self.filterController setFilterText3:@"选择商圈"];
            
            
        }
        
        if(_showingIndex == 2){
            
            [NVPopoverView slideOutPopoverView];
            [self.filterController resetFilterBtnsStates];
            if([[self.filterController filterText2] compare:title] == NSOrderedSame ){
                return;
            }
            [self.filterController setFilterText2:title];
            _curDistrict = title;
            _curCircle = nil;
            
            _filterType = 3;
            _circleMsg = nil;
            [_parser requestFilter:[GConfig getUserId] cityName:_curCity subCity:title busiCircle:nil type:nil];
            
            [self.filterController setFilterText3:@"选择商圈"];
        }
        
        if(_showingIndex == 3){
            
            [NVPopoverView slideOutPopoverView];
            [self.filterController resetFilterBtnsStates];
            if([[self.filterController filterText3] compare:title] == NSOrderedSame ){
                return;
            }
            [self.filterController setFilterText3:title];
            _curCircle = title;
        }
        
        _showingIndex = 0;
        _isEnd = false;
        _nextCur = 0;
        [_arrMer removeAllObjects];
        [_tableViewMerchant reloadData];
    
    }
    
    
}



- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString* title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"查看"]){
        PIODetailViewController * poiVC = [[[PIODetailViewController alloc] initWithNibName:@"PIODetailViewController" bundle:nil] autorelease];
        
        UINavigationController * navVc = ((UIViewController*)self.selDelegate).navigationController;
        [navVc pushViewController:poiVC animated:YES];
        
         MerchantMessage* mer = [_arrMer objectAtIndex:_curIndex];
        [poiVC updatePOIInfo:mer];
        poiVC.btnChoose1.hidden = YES;
        poiVC.btnChoose.hidden = YES;
        poiVC.btnFav.hidden = YES;

//    } else if([title isEqualToString:@"选择"]){
//        
//        PIODetailViewController * poiVC = [[[PIODetailViewController alloc] initWithNibName:@"PIODetailViewController" bundle:nil] autorelease];
//        [poiVC setSelDelegate:_selDelegate];
//        
//        UINavigationController * navVc = ((UIViewController*)self.selDelegate).navigationController;
//        [navVc pushViewController:poiVC animated:YES];
//        
//        MerchantMessage* mer = [_arrMer objectAtIndex:_curIndex];
//        [poiVC updatePOIInfo:mer];
        
//        MerchantMessage* mer = [_arrMer objectAtIndex:_curIndex];
//        [_selDelegate didSelPOI:mer];
//    } else if([title isEqualToString:@"选择并添加到收藏"]){
//        MerchantMessage* mer = [_arrMer objectAtIndex:_curIndex];
//        [_favParser reqAddFav:[GConfig getUserId] merId:[mer id]];
//        _needBack = YES;
        
    } else if([title isEqualToString:@"添加到收藏"]){
        _needBack = NO;
         MerchantMessage* mer = [_arrMer objectAtIndex:_curIndex];
        [_favParser reqAddFav:[GConfig getUserId] merId:[mer id]];
    }
    
}



- (void)didFinishReqFav:(UserFavoriteMerchantQueryResponseMessage*)favMerchants{

}
- (void)failReqFav{

}

- (void)didFinishAddMer:(CustomizedMerchantResponseMessage*)addResp{

}
- (void)failAddMer{

}

//添加收藏
- (void)didFinishAddFav:(UserFavoriteMerchantResponseMessage*)addFavResp{

    if(addFavResp != nil && [addFavResp resultCode] == 0){
         [[[iToast makeText:@"已添加到收藏"] setDuration:2000] show];
        if(_needBack){
            MerchantMessage* mer = [_arrMer objectAtIndex:_curIndex];
            [_selDelegate didSelPOI:mer];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_REFRESH_FAV object:nil];
        return;
    }
    [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
}
- (void)failAddFav{
     [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
}

//删除收藏
- (void)didFinishDel:(UserFavoriteMerchantDelResponseMessage*)delFavResp{

}
-(void)failDelFav{

}



- (void)viewDidUnload {
    [self setFilterController:nil];
    [self setTableViewMerchant:nil];
    [self setTableViewFilter:nil];
    [self setTextFieldFilter:nil];
    [super viewDidUnload];
}
- (IBAction)hideKeyBoard:(id)sender {
    [_textFieldFilter resignFirstResponder];
}
@end
